package org.surelink.radius.console;

import de.tototec.cmdoption.CmdOption;
import de.tototec.cmdoption.CmdlineParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.surelink.radius.cache.OnlineCache;
import org.surelink.radius.console.message.Request;
import org.surelink.radius.console.message.RespBase;
import org.surelink.radius.console.message.Response;
import org.surelink.radius.model.Online;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class OnlineProcess extends BaseProcess
{

    @Autowired
    private OnlineCache onlineCache;

    class Config
    {
        @CmdOption(names = {"--help"}, description = "打印帮助", isHelp = true)
        private boolean help;

        @CmdOption(names = {"get"}, description = "查询在线用户")
        private boolean get;

        @CmdOption(names = {"list"}, description = "查询在线用户列表")
        private boolean list;

        @CmdOption(names = {"online"}, description = "在线用户命令", hidden = true)
        boolean online;

        @CmdOption(names = {"limit"}, description = "查询最大用户在线数")
        private int limit = 100;

        @CmdOption(names = {"--username", "-u"}, args = {"username"}, minCount = -1, description = "用户名")
        String username;
    }


    public OnlineProcess()
    {
        setOperate("online");
    }


    @Override
    public Response process(Request req) throws Exception
    {
        Config config = new Config();
        CmdlineParser cp = new CmdlineParser(config);
        cp.setProgramName(getOperate());
        cp.parse(req.getCommand().split("\\s+"));

        if (config.help)
        {
            StringBuilder sb = new StringBuilder();
            cp.usage(sb);
            return new Response(RespBase.SUCCESS.getCode(), sb.toString());
        }

        if (config.list)
        {
            List<Online> os = onlineCache.getOnlineList(0, config.limit);
            return new Response(os);
        }
        else if (config.get)
        {
            List<Online> os = onlineCache.getOnlineByUserName(config.username);
            return new Response(os);
        }

        return RespBase.MSG_FORMAT_ERR;
    }
}
